#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

namespace SocketModule
{
    using namespace LogMudule;
    class Socket;   // 声明
    using SockPtr = std::shared_ptr<Socket>;
    // 提供一个/若干个/固定模式的socket的方法
    // 模版方法模式
    // 基类，规定创建socket的方法
    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual void SocketOrDie() = 0; // 创建socket成功就返回，失败就死亡，下同
        virtual void SetSocketOpt() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual int Accepter(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual int Fd() = 0;

        // 提供一个创建listensockfd的固定套路
        void BuildTcpSocketMethod(int port)
        {
            SocketOrDie();
            SetSocketOpt();
            BindOrDie(port);
            ListenOrDie();
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
            : _sockfd(gdefaultsockfd)
        {}
        TcpSocket(int socked)
            : _sockfd(socked)
        {}
        virtual ~TcpSocket()
        {
        }
        virtual void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if(_sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::DEBUG) << "socket create success" << _sockfd;
        }
        virtual void SetSocketOpt() override
        {

        }
        virtual bool BindOrDie(int port) override
        {
            if(_sockfd == gdefaultsockfd)   return false;
            InetAddr addr(port);
            int n = ::bind(_sockfd, addr.NetAddr(), addr.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::DEBUG) << "bind create success" << _sockfd;
            return true;
        }
        virtual bool ListenOrDie() override
        {
            if(_sockfd == gdefaultsockfd)   return false;
            int n = ::listen(_sockfd, gbacklog);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::DEBUG) << "listen create success" << _sockfd;
            return true;
        }
        // accept做两件事：1.从网络中获取文件描述符；
        // 2.获取client信息, 该信息通过传递的参数带出去：InetAddr *client
        int Accepter(InetAddr *client) override
        {
            struct sockaddr_in peer;
            socklen_t addrlen = sizeof(peer);
            int newsockfd = ::accept(_sockfd, CONV(&peer), &addrlen);
            if(newsockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                return -1;
            }
            client->SetAddr(peer, addrlen);

            return newsockfd;
        }
        // 读数据
        virtual int Recv(std::string *out) override
        {
            char buffer[1024 * 8];
            auto size = ::recv(_sockfd, buffer, sizeof(buffer), 0);
            if(size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }
            return size;
        }
        // 发数据
        virtual int Send(const std::string &in) override
        {
            auto size = ::send(_sockfd, in.c_str(), in.size(), 0);
            return size;
        }
        // 将自身的sockfd返回给上层
        virtual int Fd() override
        {
            return _sockfd;
        }
        virtual void Close() override 
        {
            if(_sockfd == gdefaultsockfd)   return;
            ::close(_sockfd);
        }

    private:
        int _sockfd;
    };

    // for test
    // int main()
    // {
            // 直接创建出TCP套接字
    //     Socket *sk = new TcpSocket();
    //     sk->BuildTcpSocketMethod(8080);
    // }
}
